﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Security;
using System.Text.RegularExpressions;
using System.Web.Security;
namespace TopModel
{
    public class MemberRepository : IPrincipal
    {
        private FormsAuthenticationTicket m_ticket;
        private Member m_member;

        public FormsAuthenticationTicket Ticket
        {
            get { return m_ticket; }
            set { m_ticket = value; }
        }

        public Member Login(string parameters)
        {
            try
            {
                string s1 = Encoding.Default.GetString(Convert.FromBase64String(parameters));
                Dictionary<string, string> d = new Dictionary<string, string>();

                if (!string.IsNullOrEmpty(s1))
                {
                    string[] s2 = s1.Split('&');
                    string[] s4 = new string[2];

                    foreach (string s3 in s2)
                    {
                        s4 = s3.Split('=');
                        if (s4.Length > 0)
                        {
                            d.Add(s4[0], s4[1]);
                        }
                    }
                    if (!string.IsNullOrEmpty(d["visitor_id"]))
                    {
                        this.m_member.UserNick=d["visitor_nick"];
                        this.m_member.UserID = d["visitor_id"];
                        this.m_member.IsAuthenticated = true;
                        string s = this.m_member.UserID + "&" + this.m_member.UserNick + "&" + this.m_member.IsAuthenticated;
                        this.m_ticket = new FormsAuthenticationTicket(0, this.m_member.UserNick, DateTime.Now, DateTime.Now.AddHours(1), true, s);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception("登陆时出现错误，请联系管理员");
            }
            return this.m_member;
        }

        public MemberRepository(FormsAuthenticationTicket ticket)
        {
            try
            {
                string s1 = ticket.UserData;
                string[] s2 = s1.Split('&');
                this.m_member = new Member() { UserID = s2[0], UserNick = s2[1], IsAuthenticated = Convert.ToBoolean(s2[2]) };
            }
            catch (Exception e)
            {
                throw new Exception("登陆时出现错误，请联系管理员");
            }
        }

        public MemberRepository()
        {
            this.m_member = new Member();
        }
        #region IPrincipal Members

        public IIdentity Identity
        {
            get { return m_member; }
        }

        public bool IsInRole(string role)
        {
            return true;
        }

        #endregion
    }
}
